package com.caocaog.market.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.caocaog.market.annotation.IgnoreAuth;
import com.caocaog.market.entity.ShopChannel;
import com.caocaog.market.entity.dto.ShopChannelTreeDTO;
import com.caocaog.market.merchant.entity.MkMerchantBasic;
import com.caocaog.market.merchant.service.MkMerchantService;
import com.caocaog.market.service.IShopChannelService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @Description: 频道信息表
 * @Author: guofeiyan
 * @Date: 2021-11-19
 * @Version: V1.0
 */
@Api(tags = "频道信息表")
@RestController
@RequestMapping("/shop/shopChannel")
@Slf4j
public class ShopChannelController extends JeecgController<ShopChannel, IShopChannelService> {
    @Autowired
    private IShopChannelService shopChannelService;
    @Autowired
    private CommonAPI commonAPI;
    @Autowired
    private MkMerchantService mkMerchantService;

    /**
     * 分页列表查询
     *
     * @param shopChannel
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "频道信息表-分页列表查询")
    @ApiOperation(value = "频道信息表-分页列表查询", notes = "频道信息表-分页列表查询")
    @GetMapping(value = "/rootList")
    public Result<?> queryPageList(ShopChannel shopChannel,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        String hasQuery = req.getParameter("hasQuery");
        Map<String, String[]> parameterMap = new HashMap<>(req.getParameterMap());
        parameterMap.remove("column");
        if ("true".equals(hasQuery)) {
            QueryWrapper<ShopChannel> queryWrapper = QueryGenerator.initQueryWrapper(shopChannel, parameterMap);
            IPage<ShopChannel> pageList = new Page<>(1, 10, 0);
            LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            System.out.println(loginUser);
            // userType 为1时是系统用户，不用管
            // userType 为2时是分站用户，分站用户就带入分站id
			if (loginUser.getUserType() == 3) {
				queryWrapper.and(i -> i.eq("site_id", loginUser.getSiteId()).or().eq("site_id", "0"));
			}
//			// userType 为3时是商家用户，商家用户看不了频道信息，所以直接返回一个空page
//			if (loginUser.getUserType() == 3) {
//				return Result.OK(pageList);
//			}
            queryWrapper.orderByDesc("is_top");
            queryWrapper.orderByDesc("create_time");
            queryWrapper.eq("parent_id", 0);
            List<ShopChannel> list = shopChannelService.queryTreeListNoPage(queryWrapper);
            pageList.setTotal(list.size());
            pageList.setRecords(list);
            return Result.OK(pageList);
        } else {
            String parentId = shopChannel.getParentId();
            if (oConvertUtils.isEmpty(parentId)) {
                parentId = "0";
            }
            shopChannel.setParentId(null);
            QueryWrapper<ShopChannel> queryWrapper = QueryGenerator.initQueryWrapper(shopChannel, req.getParameterMap());
            // 使用 eq 防止模糊查询
            queryWrapper.eq("parent_id", parentId);
            queryWrapper.orderByDesc("is_top");
            queryWrapper.orderByDesc("create_time");
            Page<ShopChannel> page = new Page<ShopChannel>(pageNo, pageSize);
            IPage<ShopChannel> pageList = shopChannelService.page(page, queryWrapper);
            return Result.OK(pageList);
        }
    }

    /**
     * 获取二级频道信息
     * @return 获取结果
     */
    @GetMapping(value = "/childChoseList")
    @ApiOperation(value = "频道信息-获取树状的频道信息")
    public Result<?> childChoseList(){
        Set<ShopChannelTreeDTO> channelList =  shopChannelService.childChoseList();
        return Result.OK("查询成功",channelList);
    }

    /**
     * 获取子数据
     *
     * @param shopChannel
     * @param req
     * @return
     */
    @AutoLog(value = "频道信息表-获取子数据")
    @ApiOperation(value = "频道信息表-获取子数据", notes = "频道信息表-获取子数据")
    @GetMapping(value = "/childList")
    public Result<?> queryPageList(ShopChannel shopChannel, HttpServletRequest req) {
        QueryWrapper<ShopChannel> queryWrapper = QueryGenerator.initQueryWrapper(shopChannel, req.getParameterMap());
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        System.out.println("====== 登陆用户：======");
        System.out.println(loginUser);
        // userType 为1时是系统用户，不用管
        // userType 为2时是分站用户，分站用户就带入分站id
        if (loginUser.getUserType() == 2) {
            queryWrapper.and(i -> i.eq("site_id", loginUser.getSiteId()).or().eq("site_id", "0"));
        }
        // userType 为3时是商家用户，找到商家的分站id
        if (loginUser.getUserType() == 3) {
            String siteId;
            if (loginUser.getSiteId() != null) {
                siteId = loginUser.getSiteId();
            } /*else if (loginUser.getMerchantId() != null) {
                siteId = this.commonAPI.getSiteIdByMerchantId(loginUser.getMerchantId());
            }*/ else {
                MkMerchantBasic mkMerchantBasic = this.mkMerchantService.findByUserId(loginUser.getId());
                if (mkMerchantBasic != null) {
                    siteId = mkMerchantBasic.getSiteId();
                } else {
                    siteId = null;
                }
            }
            System.out.println("最后siteId为：" + siteId);
            if (siteId != null) {
                queryWrapper.and(i -> i.eq("site_id", siteId).or().eq("site_id", "0"));
            } else {
                queryWrapper.eq("site_id", "0");
            }
        }
        List<ShopChannel> list = shopChannelService.list(queryWrapper);
        IPage<ShopChannel> pageList = new Page<>(1, 10, list.size());
        pageList.setRecords(list);
        return Result.OK(pageList);
    }

    /**
     * 批量查询子节点
     *
     * @param parentIds 父ID（多个采用半角逗号分割）
     * @param parentIds
     * @return 返回 IPage
     * @return
     */
    @AutoLog(value = "频道信息表-批量获取子数据")
    @ApiOperation(value = "频道信息表-批量获取子数据", notes = "频道信息表-批量获取子数据")
    @GetMapping("/getChildListBatch")
    public Result getChildListBatch(@RequestParam("parentIds") String parentIds) {
        try {
            QueryWrapper<ShopChannel> queryWrapper = new QueryWrapper<>();
            List<String> parentIdList = Arrays.asList(parentIds.split(","));
            queryWrapper.in("parent_id", parentIdList);
            LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            System.out.println(loginUser);
            // userType 为1时是系统用户，不用管
            // userType 为2时是分站用户，分站用户就带入分站id
            if (loginUser.getUserType() == 2) {
                queryWrapper.and(i -> i.eq("site_id", loginUser.getSiteId()).or().eq("site_id", "0"));
            }
            // userType 为3时是商家用户，商家用户看不了频道信息，所以直接返回一个空page
            if (loginUser.getUserType() == 3) {
                return Result.OK(new Page<>());
            }
            List<ShopChannel> list = shopChannelService.list(queryWrapper);
            IPage<ShopChannel> pageList = new Page<>(1, 10, list.size());
            pageList.setRecords(list);
            return Result.OK(pageList);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("批量查询子节点失败：" + e.getMessage());
        }
    }

    /**
     * 添加
     *
     * @param shopChannel
     * @return
     */
    @AutoLog(value = "频道信息表-添加")
    @ApiOperation(value = "频道信息表-添加", notes = "频道信息表-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody ShopChannel shopChannel) {
        if (shopChannel.getParentId() != null && !"0".equals(shopChannel.getParentId())) {
            ShopChannel p = shopChannelService.getById(shopChannel.getParentId());
            if (null != p) {
                ShopChannel p1 = shopChannelService.getById(p.getParentId());
                if (null != p1) {
                    return Result.error("最多只能有二级频道哟");
                }
            }
        } else {
            List<ShopChannel> shopChannels = shopChannelService.list(new QueryWrapper<ShopChannel>().eq("parent_id", 0));
            if (shopChannels.size() > 8) {
                return Result.error("最多只能有8个一级频道哟");
            }
        }
        shopChannelService.addShopChannel(shopChannel);
        return Result.OK("添加成功！", true);
    }

    /**
     * 编辑
     *
     * @param shopChannel
     * @return
     */
    @AutoLog(value = "频道信息表-编辑")
    @ApiOperation(value = "频道信息表-编辑", notes = "频道信息表-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody ShopChannel shopChannel) {
        shopChannelService.updateShopChannel(shopChannel);
        return Result.OK("编辑成功!", true);
    }

    @AutoLog(value = "频道信息表-顶置")
    @ApiOperation(value = "频道信息表-顶置", notes = "频道信息表-顶置")
    @PutMapping(value = "/setTop")
    public Result<?> setTop(String id) {
        return Result.OK(shopChannelService.setTop(id));
    }

    @AutoLog(value = "频道信息表-取消顶置")
    @ApiOperation(value = "频道信息表-取消顶置", notes = "频道信息表-取消顶置")
    @PutMapping(value = "/setBottom")
    public Result<?> setBottom(String id) {
        return Result.OK(shopChannelService.setBottom(id));
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "频道信息表-通过id删除")
    @ApiOperation(value = "频道信息表-通过id删除", notes = "频道信息表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        shopChannelService.deleteShopChannel(id);
        return Result.OK("删除成功!", true);
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "频道信息表-批量删除")
    @ApiOperation(value = "频道信息表-批量删除", notes = "频道信息表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.shopChannelService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！", true);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "频道信息表-通过id查询")
    @ApiOperation(value = "频道信息表-通过id查询", notes = "频道信息表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        ShopChannel shopChannel = shopChannelService.getById(id);
        if (shopChannel == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(shopChannel);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param shopChannel
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ShopChannel shopChannel) {
        return super.exportXls(request, shopChannel, ShopChannel.class, "频道信息表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, ShopChannel.class);
    }

}
